package com.zhp.farmerclient.controller;


import com.zhp.farmerclient.common.Result;
import com.zhp.farmerclient.entity.Announce;
import com.zhp.farmerclient.service.AnnounceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/notice")
@CrossOrigin//解决前端后端跨域问题
public class AnnounceController {

    @Autowired
    public AnnounceService announceService;

    //分页显示
    @GetMapping()
    public Result list(@RequestParam Integer page,
                       @RequestParam Integer size){
        return announceService.list(page,size);
    }
    //部分显示
    @GetMapping("/part")
    public Result part() {
        return announceService.part();
    }
    //详情页
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable(name = "id") int id){

        return announceService.detail(id);
    }

    //发表公告
    @PostMapping("/publish")
    public Result publish(@RequestBody Announce announce,@RequestParam("file") MultipartFile file){
        announce.setAttachment(uploadAttachment(file));
        return announceService.publish(announce);
    }

    @Value("${file.upload.path}")
    private String uploadPath;

    // 上传附件
    @PostMapping("/attachment")
    public String uploadAttachment( MultipartFile file) {
        // 获取上传文件的原始文件名
        String fileName = file.getOriginalFilename();
        // 构造目标文件的路径
        String destPath = uploadPath + File.separator + fileName;
        // 创建目标文件
        File destFile = new File(destPath);
        try {
            // 将上传的文件保存到目标文件中
            file.transferTo(destFile);
            // 返回附件的下载路径
            return destFile.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //分页显示（查询）
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String title,
                           @RequestParam(defaultValue = "") String content) {
        return announceService.page(pageNum,pageSize,title,content);
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return announceService.delete(id);
    }
    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) { // [1,2,3]
        return announceService.deletes(ids);
    }

    //新增或修改公告
    @PostMapping("/insert")
    public Result publish(@RequestBody Announce announce){
        return announceService.publish(announce);
    }
}
